<template>
  <div>
    <!-- 当前节点 -->
    <v-row 
      class="menu-tree-node py-2 px-1 hover-bg" 
      :class="{ 'bg-grey-lighten-5': level > 0 }"
      :style="{ paddingLeft: `${level * 20 + 8}px` }"
    >
      <!-- 名称列 -->
      <v-col cols="2" class="d-flex align-center">
        <!-- 展开/收起按钮 -->
        <v-btn
          v-if="node.hasChildren || (node.children && node.children.length > 0)"
          icon
          variant="text"
          @click="handleToggleExpand"
          :loading="isLoading"
          class="mr-2"
        >
          <v-icon size="16">
            {{ isExpanded ? 'mdi-chevron-down' : 'mdi-chevron-right' }}
          </v-icon>
        </v-btn>
        <div v-else class="mr-6"></div>
        
        <!-- 图标和名称 -->
        <div class="d-flex align-center">
          <v-icon v-if="node.icon" :icon="node.icon" class="mr-2" size="16"></v-icon>
          <span class="text-body-2">{{ node.menuName }}</span>
        </div>
      </v-col>

      <!-- 类型列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <v-chip
          :color="getTypeColor(node.type)"
          variant="flat"
        >
          {{ getTypeName(node.type) }}
        </v-chip>
      </v-col>

      <!-- 排序列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <span class="text-body-2">{{ node.sortNo }}</span>
      </v-col>

      <!-- 隐藏列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <v-chip
          :color="node.hidden === '0' ? 'success' : 'warning'"
          variant="flat"
        >
          {{ getNoYesName(node.hidden) }}
        </v-chip>
      </v-col>

      <!-- 总是显示列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <span class="text-body-2">{{ getNoYesName(node.alwaysShow) }}</span>
      </v-col>

      <!-- 路径列 -->
      <v-col cols="2" class="d-flex justify-center align-center">
        <span class="text-body-2 text-truncate">{{ node.url }}</span>
      </v-col>

      <!-- 组件路径列 -->
      <v-col cols="2" class="d-flex justify-center align-center">
        <span class="text-body-2 text-truncate">{{ node.component }}</span>
      </v-col>

      <!-- 标签列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <div class="d-flex gap-1 flex-wrap">
          <v-chip
            v-for="label in getLabelArray(node.label)"
            :key="label"
            :color="label === '0' ? 'info' : 'warning'"
            size="x-small"
            variant="flat"
          >
            {{ getLabelName(label) }}
          </v-chip>
        </div>
      </v-col>

      <!-- 操作列 -->
      <v-col cols="1" class="d-flex justify-center align-center">
        <div class="d-flex gap-1 justify-end">
          <v-btn
            v-if="$perms('system_menu_update')"
            icon
            variant="text"
            size="x-small"
            color="primary"
            @click="$emit('handle-edit', node)"
          >
            <v-icon size="16">mdi-pencil</v-icon>
          </v-btn>
          
          <v-menu>
            <template v-slot:activator="{ props }">
              <v-btn
                icon
                variant="text"
                size="x-small"
                v-bind="props"
              >
                <v-icon size="16">mdi-dots-vertical</v-icon>
              </v-btn>
            </template>
            <v-list density="compact">
              <v-list-item
                v-if="$perms('system_menu_insert') && node.type === '1'"
                @click="$emit('handle-add-child', node)"
              >
                <v-list-item-title>添加下级</v-list-item-title>
              </v-list-item>
              <v-list-item
                v-if="$perms('system_menu_delete')"
                @click="$emit('handle-delete', node)"
              >
                <v-list-item-title>删除</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </div>
      </v-col>
    </v-row>

    <!-- 子节点 -->
    <div v-if="isExpanded">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container" :style="{ paddingLeft: `${(level + 1) * 20 + 8}px` }">
        <v-progress-circular 
          indeterminate 
          color="primary" 
          size="16"
          width="2"
        ></v-progress-circular>
        <span class="loading-text">正在加载子菜单...</span>
      </div>
      
      <!-- 子节点列表 -->
      <div v-else-if="node.children && node.children.length > 0">
        <menu-tree-node
          v-for="child in node.children"
          :key="child.id"
          :node="child"
          :level="level + 1"
          :expanded-nodes="expandedNodes"
          :tmp-tree-data="tmpTreeData"
          @toggle-expand="$emit('toggle-expand', $event)"
          @load-children="$emit('load-children', $event)"
          @handle-add-child="$emit('handle-add-child', $event)"
          @handle-edit="$emit('handle-edit', $event)"
          @handle-delete="$emit('handle-delete', $event)"
        />
      </div>
      
      <!-- 无子节点提示 -->
      <div v-else class="loading-container" :style="{ paddingLeft: `${(level + 1) * 20 + 8}px` }">
        <span class="no-data-text">暂无子菜单</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, ref } from 'vue';

interface Props {
  node: any;
  level: number;
  expandedNodes: Set<string>;
  tmpTreeData: Record<string, any>;
}

const props = defineProps<Props>();
const { proxy } = getCurrentInstance()!;

// 添加加载状态
const isLoading = ref(false);

const emit = defineEmits([
  'toggle-expand',
  'load-children',
  'handle-add-child',
  'handle-edit',
  'handle-delete'
]);

// 是否展开
const isExpanded = computed(() => props.expandedNodes.has(props.node.id));

// 处理展开/收起
const handleToggleExpand = async () => {
  // 如果是收起操作，直接执行
  if (isExpanded.value) {
    emit('toggle-expand', props.node.id);
    return;
  }
  
  // 如果是展开操作且没有子节点，则先加载
  if (!props.node.children || props.node.children.length === 0) {
    isLoading.value = true;
    try {
      await emit('load-children', props.node);
      // 只有加载成功后才展开
      emit('toggle-expand', props.node.id);
    } catch (error) {
      console.error('加载子节点失败:', error);
    } finally {
      isLoading.value = false;
    }
  } else {
    // 如果已有子节点，直接展开
    emit('toggle-expand', props.node.id);
  }
};

// 获取类型名称
const getTypeName = (type: string) => {
  return proxy?.$getDictNameByValue('menu_type', type) || type;
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    '1': 'primary',
    '2': 'warning', 
    '3': 'info'
  };
  return colors[type] || 'default';
};

// 获取是否名称
const getNoYesName = (value: string) => {
  return proxy?.$getDictNameByValue('no_yes', value) || value;
};

// 获取标签数组
const getLabelArray = (label: string) => {
  if (!label) return [];
  return label.split(',').filter(l => l.trim());
};

// 获取标签名称
const getLabelName = (label: string) => {
  return proxy?.$getDictNameByValue('menu_role_label', label) || label;
};
</script>

<style scoped>
.menu-tree-node {
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.menu-tree-node:hover {
  background-color: #f5f5f5;
}

.hover-bg:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 8px 0;
  color: #666;
}

.loading-text {
  margin-left: 8px;
  font-size: 0.875rem;
}

/* 无数据提示样式 */
.no-data-text {
  color: #999;
  font-style: italic;
  font-size: 0.875rem;
}
</style> 